<template>
	<view class="edit-profile">
		<view class="form-item">
			<text>头像</text>
			<!-- 给图片添加类名 avatar-image -->
			<image :src="avatar" mode="aspectFill" @click="chooseAvatar" class="avatar-image"></image>
		</view>
		<view class="form-item">
			<text>昵称</text>
			<input v-model="nickName" placeholder="请输入昵称"></input>
		</view>
		<view class="form-item">
			<text>性别</text>
			<!-- 修正 :range 前的空格 -->
			<picker mode="selector" :value="sex" :range="sexArr" @change="changeSex">
				<view>{{ sexArr[sex] }}</view>
			</picker>
		</view>
		<view class="form-item">
			<text>学号</text>
			<input v-model="studentId" placeholder="请输入学号"></input>
		</view>
		<button @click="saveProfile">保存</button>
	</view>
</template>

<script>
	import {
		editProfile,
		getProfile
	} from "@/api/user.js";
	import {
		uploadAvatar
	} from "@/api/system/user.js"
	import config from '@/config'
	export default {
		data() {
			return {
				avatar: '',
				nickName: '',
				sex: 0,
				studentId: '',
				sexArr: ['男', '女']
			};
		},
		onLoad() {
			this.getProfileInfo()
		},
		methods: {
			changeSex(e) {
				this.sex = e.detail.value;
			},
			getProfileInfo() {
				getProfile().then(res => {
					this.nickName = res.data.nickName;
					this.sex = res.data.sex;
					this.avatar = config.baseUrl + res.data.avatar
					this.studentId = res.data.studentId
				})
			},
			chooseAvatar() {
				uni.chooseImage({
					count: 1,
					// 获取图片本地路径
					success: (res) => {
						const tempFilePaths = res.tempFilePaths
						const tempFiles = res.tempFiles
						const data = {
							filePath: tempFilePaths[0],
							name: 'avatarfile',
						}
						uploadAvatar(data).then(res => {
							// 上传成功后做回显操作
							this.avatar = config.baseUrl + res.imgUrl;
						})
					}
				})
			},
			saveProfile() {
				// 准备要发送的数据
				const data = {
					avatar: this.avatar,
					nickName: this.nickName,
					sex: this.sex,
					studentId: this.studentId
				};
				editProfile(data).then(res => {
					console.log("修改用户信息" + res)
				})
			}
		}
	};
</script>

<style lang="scss">
	.edit-profile {
		padding: 20px;
	}

	.form-item {
		margin-bottom: 20px;
		display: flex;
		align-items: center;
	}

	text {
		width: 100px;
	}

	// 新增头像图片样式
	.avatar-image {
		width: 100px;
		height: 100px;
		margin-left: 20px;
		border-radius: 50%; // 使元素呈圆形
		border: 2px solid #ccc; // 添加灰色边框，宽度为 2px
		overflow: hidden; // 隐藏超出圆形范围的内容
	}

	input {
		margin-left: 20px;
		border: 1px solid #ccc;
		padding: 10px;
		width: 200px;
		height: 40px;
		box-sizing: border-box;
	}

	picker {
		margin-left: 20px;
	}

	button {
		margin-top: 20px;
	}
</style>